package com.penghaisoft.microwms.product.service.impl;

import com.penghaisoft.microwms.common.Constant;
import com.penghaisoft.microwms.common.data.model.MdProModel;
import com.penghaisoft.microwms.common.data.model.ProBarcode;
import com.penghaisoft.microwms.common.data.model.ProHandOutSn;
import com.penghaisoft.microwms.common.data.model.ProSellOutSn;
import com.penghaisoft.microwms.common.dto.ProBarcodeDto;
import com.penghaisoft.microwms.common.dto.Resp;
import com.penghaisoft.microwms.common.dto.TransResult;
import com.penghaisoft.microwms.common.page.Pager;
import com.penghaisoft.microwms.common.service.BaseService;
import com.penghaisoft.microwms.common.service.IWmsCommonService;
import com.penghaisoft.microwms.common.wms.model.*;
import com.penghaisoft.microwms.product.dao.*;
import com.penghaisoft.microwms.product.service.IProBarcodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * <p>
 * 业务逻辑实现类
 * </p>
 *
 * @author
 * @createDate
 **/
@Service("proBarcodeService")
public class ProBarcodeServiceImpl extends BaseService implements IProBarcodeService {
    @Resource
    private ProBarcodeMapper proBarcodeMapper;
    @Resource
    private ProStorageSnMapper proStorageSnMapper;
    @Resource
    private ProOrderInSnMapper proOrderInSnMapper;
    @Resource
    private ProCheckInMapper proCheckInMapper;
    @Resource
    private ProScrapOutSnMapper proScrapOutSnMapper;
    @Resource
    private ProSellOutSnMapper proSellOutSnMapper;
    @Resource
    private ProHandOutSnMapper proHandOutSnMapper;
    @Autowired
    private IWmsCommonService wmsCommonService;
    @Resource
    private MsbarCodeMapper msbarCodeMapper;
    @Resource
    private MdProModelMapper mdProModelMapper;

    /**
     * 新增记录
     *
     * @param
     * @return
     */
    @Override
    public Resp create(ProBarcode proBarcode) {
        proBarcodeMapper.create(proBarcode);
        return success();
    }

    @Override
    public Resp codeCreate(ProCheckIn proCheckIn) {
    	if(null==proCheckIn.getGmtProduct()){
    		return fail("请联系运维人员！");
    	}
        List<ProBarcode> proBarcodes = new ArrayList<>();
        List<String> barcodes = new ArrayList<>();
        List<String> codes = new ArrayList<>();
        StringBuffer barcode = new StringBuffer();
        SimpleDateFormat sdfGmt = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
			date = sdfGmt.parse(sdfGmt.format(proCheckIn.getGmtProduct()));
		} catch (ParseException e) {
			e.printStackTrace();
		}
        //根据生产时间查询当前条码最大值，获取大卷筒数值，新条码以最大值+1为起始值
/*        ProBarcode gmtProduct = new ProBarcode();
        gmtProduct.setGmtProduct(date);*/
//        proBarcode.setActiveFlag("1");
//        String bigNum = proBarcodeMapper.getBigNum(gmtProduct);
//        ProCheckIn obj = new ProCheckIn();
//        obj.setCheckInId(proCheckIn.getCheckInId());
        ProCheckIn condition = new ProCheckIn();
    	condition.setCheckInNo(proCheckIn.getCheckInNo());
    	List<ProCheckIn> proCheckIns = proCheckInMapper.queryList(null, condition);
        condition.setGmtProduct(date);
/*        String bigNum = proCheckInMapper.getBigNum(condition);
        if(null==bigNum){
        	bigNum = "00";
        }
        Integer startNum = Integer.valueOf(bigNum);*/
        // 生产班组+大卷筒号 例如：304
        Integer startNum = proCheckIn.getBigNumber();

        //条码拼接前缀 00代表第一次生产 10报废后重新生产 20退货
        barcode.append("00");
        //条码拼接第一部分：生产时间
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        barcode.append(sdf.format(proCheckIn.getGmtProduct()).substring(2));
/*        //条码拼接第二部分：生产班组
        barcode.append(Integer.parseInt(proCheckIn.getProductionTeam()));*/
        //条码拼接第三部分：【生产班组+大卷筒号】如【304】
        if(startNum<=100 || startNum >999){
            return fail("大卷筒号输入错误，请重新操作！");
        }else {
            //拼接大卷筒生产机器号
            barcode.append(proCheckIn.getMachineNumber());
            //拼接大卷筒号
            barcode.append(startNum);
        }
/*        for (int i=1;i<=proCheckIn.getBigNumber();i++){
            int j = i+startNum;
            if (j<10){
            	barcode.append("0");
            	barcode.append(j);
            }else {
            	barcode.append(j);
            }
            barcodes.add(barcode.toString());
            barcode.delete(barcode.length()-2, barcode.length());
        }
        barcode.setLength(0);*/
        //条码拼接第四部分:复卷班组
        barcode.append(Integer.parseInt(proCheckIn.getRewindingTeam()));
/*        for (int i = 0;i<barcodes.size();i++){
        	barcode.append("");
        	barcode.append(barcodes.get(i));
        	barcode.append(Integer.parseInt(proCheckIn.getRewindingTeam()));
            codes.add(barcode.toString());
            barcode.setLength(0);
        }
        barcodes.clear();*/
        //条码拼接第五部分：复卷个数序号
        for (int i=1;i<=proCheckIn.getRewindingNumber();i++){
            barcode.append(i);
            codes.add(barcode.toString());
            barcode.delete(barcode.length()-1, barcode.length());
        }
/*        for (int i=0;i<codes.size();i++){
            for (int j=1;j<=proCheckIns.size();j++){
            	barcode.append("");
            	barcode.append(codes.get(i));
            	barcode.append(j);
                barcodes.add(barcode.toString());
                barcode.setLength(0);
            }
        }
        codes.clear();*/
        //条码拼接第六部分：复卷次数序号
        barcode.setLength(0);
        if (proCheckIn.getRewindingCount() > 4 ){
            int a = 4;
            int b = 1;
            if (proCheckIn.getRewindingCount() == 1234){
                a = 4;
            }else if (proCheckIn.getRewindingCount() == 123){
                a = 3;
            }else if (proCheckIn.getRewindingCount() == 12){
                a = 2;
            }else if (proCheckIn.getRewindingCount() == 234){
                b = 2; a = 4;
            }else if (proCheckIn.getRewindingCount() == 23){
                b = 2; a = 3;
            }else if (proCheckIn.getRewindingCount() == 34){
                b = 3; a = 4;
            }
            for (int i=b;i<=a;i++){
                for (int j=0;j<codes.size();j++){
                    barcode.append("");
                    barcode.append(codes.get(j));
                    barcode.append(i);
                    barcodes.add(barcode.toString());
                    barcode.setLength(0);
                }
            }
        }else if (proCheckIn.getRewindingCount() >= 1 && proCheckIn.getRewindingCount() <= 4){
            for (int j=0;j<codes.size();j++){
                barcode.append("");
                barcode.append(codes.get(j));
                barcode.append(proCheckIn.getRewindingCount());
                barcodes.add(barcode.toString());
                barcode.setLength(0);
            }
        }

/*        for (int i=0;i<barcodes.size();i++){
            for (int j=1;j<=proCheckIn.getRewindingCount();j++){
            	barcode.append("");
            	barcode.append(barcodes.get(i));
            	barcode.append(j);
                codes.add(barcode.toString());
                barcode.setLength(0);
            }
        }*/
        int len = barcodes.get(0).length();
        for (int i=0;i<barcodes.size();i++){
            ProBarcode proBarcode = new ProBarcode();
            proBarcode.setBarcode(barcodes.get(i));
            for(int j=0;j<proCheckIns.size();j++){
            	if(barcodes.get(i).substring(len-2, len-1).equals(proCheckIns.get(j).getUserDefined5())){
            		proBarcode.setModel(proCheckIns.get(j).getModel());
            		proBarcode.setProductName(proCheckIns.get(j).getProductName());
                    proBarcode.setDensity(proCheckIns.get(j).getDensity());
                    proBarcode.setSpec(proCheckIns.get(j).getSpec());
                    proBarcode.setGrade(proCheckIns.get(j).getGrade());
                    proBarcode.setLevel(proCheckIns.get(j).getLevel());
                    proBarcode.setUserDefined5(proCheckIns.get(j).getUserDefined5());//复卷个数
                    proBarcode.setUserDefined9(proCheckIn.getRewindingTeam());//复卷班组
                    proBarcode.setUserDefined10(proCheckIns.get(j).getUserDefined10());//生产类型
//            		该型号目前登记数量
            		int amount = proCheckIns.get(j).getAmount()!=null ? 
            				proCheckIns.get(j).getAmount() : 0;
            		proCheckIns.get(j).setAmount(amount+1);
            	}
            }
            
            proBarcode.setMachineNumber(Integer.valueOf(proCheckIn.getMachineNumber()));
//            proBarcode.setType(proCheckIn.getType());
            proBarcode.setType(null);
//            proBarcode.setUnit(proCheckIn.getUserDefined1());
            proBarcode.setUserDefined2(proCheckIn.getCheckInNo());
            proBarcode.setCreateBy(proCheckIn.getLoginName());
            proBarcode.setGmtCreate(new Date());
            proBarcode.setLastModifiedBy(proCheckIn.getLoginName());
            proBarcode.setGmtModified(new Date());
            proBarcode.setUnit(proCheckIn.getUnit());
            proBarcode.setStatus("0");
            proBarcode.setUserDefined1("0");
            proBarcode.setActiveFlag("1");
            proBarcode.setGmtProduct(date);
//          DJ：登记入库，BF：报废入库
            proBarcode.setUserDefined4("DJ");
            proBarcodeMapper.create(proBarcode);

            // 往条码打印接口表中插入数据
            MsbarCode msbarCode = new MsbarCode();
            msbarCode.setBarCode(proBarcode.getBarcode());
            msbarCode.setBarCodeSize(Constant.CODE_ONE);
            msbarCode.setModel(proBarcode.getModel());
            msbarCode.setProductName(proBarcode.getProductName());
            msbarCode.setDensity(proBarcode.getDensity());
            msbarCode.setSpec(proBarcode.getSpec());
            msbarCode.setGrade(proBarcode.getGrade());
            msbarCode.setUpdateDate(new Date());
            msbarCode.setIsPrint(new Boolean("0"));
            // 批次号
            msbarCode.setBatchCode(proCheckIn.getCheckInNo());
            msbarCodeMapper.create(msbarCode);
        }
        for(int i = 0;i < proCheckIns.size();i++){
        	proCheckIns.get(i).setUserDefined2("1");
	        proCheckInMapper.updateBySelect(proCheckIns.get(i));
        }
        return success();
    }

    /**
     * 重新包装
     */
    @Override
    public Resp packScrap(ProCheckIn proCheckIn){
    	StringBuffer barcodeNew = new StringBuffer();
    	Date now = new Date();
    	String oldBarcode = proCheckIn.getUserDefined9();
        int prefix = Integer.valueOf(oldBarcode.substring(0,2));
        if(prefix == 0){
        	barcodeNew.append("10").append(oldBarcode.substring(2));
        }else if(prefix > 19){
        	String barcode = oldBarcode.substring(2);
        	int endIndex = barcode.length() - 3;
        	ProBarcode tmp = new ProBarcode();
			tmp.setActiveFlag("1");
			tmp.setBarcode(barcode);
			tmp.setUserDefined4("BF");
			Long countBarcode = proBarcodeMapper.queryCount(tmp);
			if(countBarcode == 0){
				barcodeNew.append("10").append(barcode);
			}else{
				List<ProBarcode> list = proBarcodeMapper.getMaxBarCode(tmp);
				if(list.size() > 1){
					return fail("请联系运维人员！");
				}else{
					prefix = Integer.valueOf(list.get(0).getBarcode().substring(0,2)) + 1;
					barcodeNew.append(prefix).append(barcode.substring(0, endIndex));
				}
			}
        }else if(prefix > 9 && prefix < 19){
        	barcodeNew.append(prefix+1).append(oldBarcode.substring(2,oldBarcode.length()-3));
        }else if(prefix == 19){
        	return fail("报废次数已达上限！");
        }
      //重卷班组
        int rewindTeam = Integer.valueOf(proCheckIn.getUserDefined6());
        barcodeNew.append(rewindTeam).append("11");
//        获取报废条码信息
        ProScrapOutSn proScrapOutSn = new ProScrapOutSn();
        proScrapOutSn.setBarcode(proCheckIn.getUserDefined9());
        List<ProScrapOutSn> scrapOutSnList = proScrapOutSnMapper.queryByAny(proScrapOutSn);
        if(scrapOutSnList.size() > 1){
        	return fail("请联系运维人员！");
        }
        ProScrapOutSn scrapOutSn = scrapOutSnList.get(0);
        scrapOutSn.setUserDefined4("1");
        scrapOutSn.setUserDefined2(barcodeNew.toString());
        proScrapOutSnMapper.updateBySelect(scrapOutSn);
//        插入下线明细表
        ProBarcode proBarcode = new ProBarcode();
        proBarcode.setBarcode(barcodeNew.toString());
        proBarcode.setModel(scrapOutSn.getModel());
		proBarcode.setProductName(scrapOutSn.getProductName());
        proBarcode.setDensity(scrapOutSn.getDensity());
        proBarcode.setSpec(scrapOutSn.getSpec());
        proBarcode.setGrade(proCheckIn.getGrade());
        proBarcode.setLevel(proCheckIn.getLevel());
//        proBarcode.setMachineNumber(scrapOutSn.getMachineNumber());
        proBarcode.setMachineNumber(Integer.valueOf(proCheckIn.getMachineNumber()));
        proBarcode.setType(scrapOutSn.getType());
        proBarcode.setUserDefined2(proCheckIn.getCheckInNo());//批次号
        proBarcode.setCreateBy(proCheckIn.getLoginName());
        proBarcode.setGmtCreate(now);
        proBarcode.setLastModifiedBy(proCheckIn.getLoginName());
        proBarcode.setGmtModified(now);
        proBarcode.setUnit(scrapOutSn.getUnit());
        proBarcode.setStatus("0");
        proBarcode.setUserDefined1("0");
        proBarcode.setActiveFlag("1");
        proBarcode.setGmtProduct(now);
//          DJ：登记入库，BF：报废入库
        proBarcode.setUserDefined4("BF");
        proBarcodeMapper.create(proBarcode);

//        往条码打印接口表中插入数据
        MsbarCode msbarCode = new MsbarCode();
        msbarCode.setBarCode(proBarcode.getBarcode());
        msbarCode.setBarCodeSize(Constant.CODE_ONE);
        msbarCode.setModel(proBarcode.getModel());
        msbarCode.setProductName(proBarcode.getProductName());
        msbarCode.setDensity(proBarcode.getDensity());
        msbarCode.setSpec(proBarcode.getSpec());
        msbarCode.setGrade(proBarcode.getGrade());
        msbarCode.setUpdateDate(new Date());
        msbarCode.setIsPrint(new Boolean("0"));
        // 批次号
        msbarCode.setBatchCode(proCheckIn.getCheckInNo());
        msbarCodeMapper.create(msbarCode);
        
    	return success();
    }

    /**
     * 拆分报废
     */
    @Override
    public Resp splitScrap(ProCheckIn proCheckIn){
    	// 获得 品名、定量、规格、单位
        MdProModel mdProModel = new MdProModel();
        mdProModel.setModel(proCheckIn.getModel());
        List<MdProModel> models = mdProModelMapper.queryByAny(mdProModel);
        // 完整条码 由 标识段+条码段 组成，如： 00 181107111111，
        // 其中 00 代表新建条码 10-19代表报废后重建条码 20-29代表退货后重建条码
        Resp resp = new Resp();
        StringBuffer stb = new StringBuffer();
        String[] strs = proCheckIn.getModel().split("-");
        ProBarcode proBarcode = new ProBarcode();
        proBarcode.setModel(proCheckIn.getModel());
        proBarcode.setProductName(strs[0]);
        proBarcode.setDensity(strs[1]);
        proBarcode.setSpec(strs[2]);
        proBarcode.setMachineNumber(Integer.valueOf(proCheckIn.getMachineNumber()));
//        proBarcode.setMachineNumber(Integer.valueOf(models.get(0).getMachineNumber()));//型号对应 生产机器号
        proBarcode.setGrade(proCheckIn.getGrade());
        proBarcode.setLevel(proCheckIn.getLevel());
        proBarcode.setType("0");  // 类型：0正品，1样品
        proBarcode.setStatus("0"); // 状态 0：未打印 1：已打印
        proBarcode.setGmtProduct(new Date());
        proBarcode.setUserDefined1("0"); // 入库状态：0 未入库 1已入库
        proBarcode.setUserDefined2(proCheckIn.getCheckInNo()); // 批次号
        proBarcode.setUserDefined4("BF"); // DJ：新入库，BF：报废入库  TH：退货入库
        proBarcode.setUserDefined5(proCheckIn.getUserDefined5()); // 横向切割位次：1、2、3
        proBarcode.setCreateBy(proCheckIn.getLoginName());
        proBarcode.setGmtCreate(new Date());
        proBarcode.setGmtModified(new Date());
        proBarcode.setActiveFlag("1");
        proBarcode.setUnit("KG");

        int x = 0;
        String barcode = proCheckIn.getUserDefined9();
        String a = barcode.substring(0,2); // 截取 标识段：前两位
        String b = barcode.substring(2);   // 截取 条码段：第三位到最后
        String c = ""; // 新的标识段

        int number = Integer.valueOf(a);
        if (number<10){
            number = 10;
        }else if (number>=10 && number<20){
            number = number + 1;
        }else {
            ProBarcode proBarcode1 = new ProBarcode();
            proBarcode1.setBarcode(b);
            proBarcode1.setUserDefined4("BF");
            long count = proBarcodeMapper.queryCount(proBarcode1);   // 查询条码是否报废过
            if (count>0){
                List<ProBarcode> barcodes = proBarcodeMapper.getMaxBarCode(proBarcode1); // 根据 条码段获取当前值最大的条码
                if (barcodes.size()>1){
                    return fail("报废条码重复，请联系运维人员！");
                }else {
                    ProBarcode proBarcode2 = barcodes.get(0);
                    a = proBarcode2.getBarcode().substring(0,2);
                    number = Integer.valueOf(a) + 1;
                }
            }else {
                number = 10;
            }
        }
        c = c + number;
        barcode = c + b;

        String code = barcode.substring(0,15); // 截取 条码的前15位（2位标识码+1位生成机号+12位条码），后面三位需要新增或修改后拼接
        String lastThree = "";  // 最后三位
        lastThree = lastThree + Integer.valueOf(proCheckIn.getUserDefined6()) + proCheckIn.getUserDefined5();
        int m = Integer.valueOf(proCheckIn.getUserDefined8());
        if (m == 0){
            return fail("请填入重卷次数！");
        }
        for (int i=1;i<=m;i++){
            String last = new String("");
            last = code + lastThree + i;
            proBarcode.setBarcode(last);
            x += proBarcodeMapper.create(proBarcode);

            MsbarCode msbarCode = new MsbarCode();
            msbarCode.setBarCode(proBarcode.getBarcode());
            msbarCode.setBarCodeSize("1");
            msbarCode.setModel(proBarcode.getModel());
            msbarCode.setProductName(proBarcode.getProductName());
            msbarCode.setDensity(proBarcode.getDensity());
            msbarCode.setSpec(proBarcode.getSpec());
            msbarCode.setGrade(proBarcode.getGrade());
            msbarCode.setUpdateDate(new Date());
            msbarCode.setBatchCode(proBarcode.getUserDefined2());
            msbarCode.setIsPrint(false);
            msbarCode.setPrintDate(null);
            msbarCodeMapper.create(msbarCode);
        }

        ProScrapOutSn scrapOutSn = new ProScrapOutSn();
        scrapOutSn.setBarcode(proCheckIn.getUserDefined9());
        scrapOutSn.setUserDefined4("1");
        proScrapOutSnMapper.updateBySelect(scrapOutSn);

        resp.setCode(String.valueOf(x));
        return resp;
    }


    /**
     * 删除记录（逻辑删除）
     *
     * @param
     * @return
     */
    @Override
    public Resp delete(ProBarcode proBarcode) {
        proBarcodeMapper.delete(proBarcode);
        return success();
    }

    /**
     * 查询列表
     *
     * @param
     * @param
     * @return
     */
    @Override
    public Pager<ProBarcode> findListByCondition(int page, int rows, ProBarcode condition) {
        Pager<ProBarcode> pager = new Pager<>();
        pager.setPage(page);
        pager.setRows(rows);
        condition.preQuery();
        List<ProBarcode> records = proBarcodeMapper.queryList(pager, condition);
        long size = proBarcodeMapper.queryCount(condition);
        pager.setRecords(records);
        pager.setTotalCount(size);
        return pager;
    }

    /**
     * 查询单条
     *
     * @param id
     * @return
     */
    @Override
    public ProBarcode findById(String id) {
        return proBarcodeMapper.queryById(id);
    }

    /**
     * 修改记录
     *
     * @param
     * @return
     */
    @Override
    public Resp update(ProBarcode proBarcode) {
        proBarcodeMapper.updateBySelect(proBarcode);
        MsbarCode msbarCode = new MsbarCode();
        msbarCode.setBarCode(proBarcode.getBarcode());
        msbarCode.setModel(proBarcode.getModel());
        msbarCode.setProductName(proBarcode.getProductName());
        msbarCode.setDensity(proBarcode.getDensity());
        msbarCode.setSpec(proBarcode.getSpec());
        msbarCode.setGrade(proBarcode.getGrade());
        msbarCode.setUpdateDate(new Date());
        msbarCode.setIsPrint(new Boolean("0"));
        msbarCodeMapper.updateByBarcode(msbarCode);
        return success();
    }

    /**
     * @param proBarcodeDto
     * @return
     * @Title downlineScanBarcode
     * @Description 下线扫码入库
     * @author luoteng
     * @date 2018年6月7日:上午10:08:12
     */
    @Transactional
    @Override
    public TransResult downlineScanBarcode(ProBarcodeDto proBarcodeDto) {
        TransResult result = new TransResult();
        result.setCode(Constant.SUCCESS);

        Date now = new Date();

        ProBarcode proBarcode = new ProBarcode();
        proBarcode.setBarcode(proBarcodeDto.getBarcode());
        proBarcode.setActiveFlag("1");

        List<ProBarcode> proBarcodeList = proBarcodeMapper.queryByAny(proBarcode);
        if (proBarcodeList == null || proBarcodeList.isEmpty()) {
            result.setCode(Constant.FAIL);
            result.setMsg("该条码未下线。");
            return result;
        } else if (proBarcodeList.size() > 1) {
            result.setCode(Constant.FAIL);
            result.setMsg("该下线条码重复。");
            return result;
        } else {
        	ProBarcode tmp = proBarcodeList.get(0);
        	ProStorageSn proStorageSn = new ProStorageSn();
        	proStorageSn.setBarcode(proBarcodeDto.getBarcode());
        	List<ProStorageSn> storageSnList = proStorageSnMapper.queryList(null,proStorageSn);
        	if(storageSnList.size() > 0){
        		if("0".equals(storageSnList.get(0).getActiveFlag())){
        			result.setCode(Constant.FAIL);
        			result.setMsg("该条码已报废!");
                    return result;
        		}else if("2".equals(storageSnList.get(0).getBarcodeStatus())){
        			result.setCode(Constant.FAIL);
        			result.setMsg("该条码已出库!");
                    return result;
        		}else{
        			 result.setCode(Constant.FAIL);
                     result.setMsg("该条码已入库!");
                     return result;
        		}
        	}
        	else{
   			 proStorageSn.setModel(tmp.getModel());
   			 proStorageSn.setType(tmp.getType());
   			 proStorageSn.setProManuDate(now);
   			 proStorageSn.setProPlanDate(tmp.getGmtCreate());
   			 proStorageSn.setWaCode(proBarcodeDto.getWaCode());
   			 proStorageSn.setWlCode(proBarcodeDto.getWlCode());
//	        	0：可用 1：冻结 2：已出库 3：抽检冻结
   			 proStorageSn.setBarcodeStatus("0");
   	         proStorageSn.setCreateBy(proBarcodeDto.getLoginName());
   	         proStorageSn.setGmtCreate(now);
   	         proStorageSn.setLastModifiedBy(proBarcodeDto.getLoginName());
	         proStorageSn.setGmtModified(now);
   			 proStorageSn.setActiveFlag("1");
   			 proStorageSn.setWeight(new BigDecimal(proBarcodeDto.getWeight()));
   			 proStorageSn.setProductName(tmp.getProductName());
   	         proStorageSn.setDensity(tmp.getDensity());
   	         proStorageSn.setSpec(tmp.getSpec());
   	         proStorageSn.setMachineNumber(tmp.getMachineNumber());
   	         proStorageSn.setGrade(tmp.getGrade());
   	         proStorageSn.setLevel(tmp.getLevel());
   	         proStorageSn.setUnit(tmp.getUnit());
   	         if("BF".equals(tmp.getUserDefined4())){
   	        	proStorageSn.setUserDefined4("BFIN");//入库时标记条码类型  报废后产生的新条码
   	         }
   	         else{
   	        	 proStorageSn.setUserDefined4(tmp.getUserDefined4());//入库时标记条码类型  DJ：新入库，BF：报废入库  TH：退货入库
   	         }
   	         proStorageSnMapper.create(proStorageSn);
   	         
             result.setMsg("该条码未入库!");
//        	}
            
//	        	入库状态 0：创建 1：已下线入库
//            if (tmp.getUserDefined1() != null && tmp.getUserDefined1().equals("1")) {
//                result.setCode(Constant.FAIL);
//                result.setMsg("该条码已经下线入库。");
//                return result;
//            }
//	        	入库状态 0：创建 1：已下线入库
            tmp.setUserDefined1("1");
//            tmp.setWlCode(Constant.DEFAULT_WL_CODE);
            tmp.setWaCode(proBarcodeDto.getWaCode());
            tmp.setWlCode(proBarcodeDto.getWlCode());
//            tmp.setGmtCreate(now);
            tmp.setLastModifiedBy(proBarcodeDto.getLoginName());
            tmp.setGmtModified(now);
            proBarcodeMapper.updateBySelect(tmp);
            
            ProOrderInSn proOrderInSn = new ProOrderInSn();
            proOrderInSn.setBarcode(tmp.getBarcode());
            proOrderInSn.setActiveFlag("1");
            proOrderInSn.setUnit(tmp.getUnit());
            proOrderInSn.setModel(tmp.getModel());
            proOrderInSn.setType(tmp.getType());
            proOrderInSn.setProPlanDate(tmp.getGmtCreate());
            proOrderInSn.setWaCode(proBarcodeDto.getWaCode());
            proOrderInSn.setWlCode(proBarcodeDto.getWlCode());
            proOrderInSn.setWeight(new BigDecimal(proBarcodeDto.getWeight()));
//            入库状态 0：创建 1：已下线入库
            proOrderInSn.setBarcodeStatus("1");
            proOrderInSn.setCreateBy(proBarcodeDto.getLoginName());
            proOrderInSn.setGmtCreate(now);
            proOrderInSn.setProductName(tmp.getProductName());
            proOrderInSn.setDensity(tmp.getDensity());
            proOrderInSn.setSpec(tmp.getSpec());
            proOrderInSn.setMachineNumber(tmp.getMachineNumber());
            proOrderInSn.setGrade(tmp.getGrade());
            proOrderInSn.setLevel(tmp.getLevel());
            proOrderInSn.setProInDate(now);
            proOrderInSn.setUserDefined1(tmp.getUserDefined9());
            proOrderInSnMapper.create(proOrderInSn);
	            
            ProCheckIn proCheckIn = new ProCheckIn();
            proCheckIn.setInAmount(1);
            proCheckIn.setCheckInNo(tmp.getUserDefined2());
            proCheckIn.setUserDefined5(tmp.getUserDefined5());
            proCheckIn.setLastModifiedBy(proBarcodeDto.getLoginName());
            proCheckIn.setGmtModified(now);
            proCheckInMapper.updateInAmount(proCheckIn);

        	}
            List<ProBarcode> rtnList = new ArrayList<ProBarcode>();
            rtnList.add(tmp);
            result.setList(rtnList);
        }

        return result;
    }

    @Override
    public TransResult downlineDelBarcode(ProBarcodeDto proBarcodeDto) {
        // TODO Auto-generated method stub
        return null;
    }

	@Override
	public List<ProBarcode> queryList(ProBarcode proBarcode) {
		return proBarcodeMapper.queryList(null, proBarcode);
	}

//	@Override
//	public TransResult returnsScan(ProBarcodeDto proBarcodeDto) {
//		TransResult result = new TransResult();
//		result.setCode(Constant.SUCCESS);
//		
//		ProSellOutSn proSellOutSn = new ProSellOutSn();
//		proSellOutSn.setBarcode(proBarcodeDto.getBarcode());
//		proSellOutSn.setActiveFlag("1");
//		Long countSellOut = proSellOutSnMapper.queryCount1(proSellOutSn);
//		ProHandOutSn proHandOutSn = new ProHandOutSn();
//		proHandOutSn.setBarcode(proBarcodeDto.getBarcode());
//		proHandOutSn.setActiveFlag("1");
//		Long countHandOut = proHandOutSnMapper.queryCount1(proHandOutSn);
//		Long count = countSellOut + countHandOut;
//		if(count > 1){
//			result.setCode(Constant.FAIL);
//			result.setMsg("请联系运维人员");
//			return result;
//		}else if(count == 0){
//			result.setCode(Constant.FAIL);
//			result.setMsg("请扫描退货成品条码！");
//			return result;
//		}
//			StringBuffer barcodeNew = new StringBuffer();
//		ProStorageSn condition = new ProStorageSn();
//		condition.setBarcode(proBarcodeDto.getBarcode());
//		condition.setUserDefined4("0");
//		condition.setBarcodeStatus("2");
//		condition.setActiveFlag("1");
//		List<ProStorageSn> proStorageSns = proStorageSnMapper.queryByAny(condition);
//		if(proStorageSns.size() == 1){
//			String barcodeOld = proStorageSns.get(0).getBarcode();
//			Integer prefix = Integer.valueOf(barcodeOld.substring(0, 2));
//			if(prefix == 0){
//				barcodeNew.append("20").append(barcodeOld.substring(2));
//			}else if(10 <= prefix && prefix < 20){
//				String barcode = barcodeOld.substring(2);
//				ProBarcode tmp = new ProBarcode();
//				tmp.setActiveFlag("1");
//				tmp.setBarcode(barcode);
//				tmp.setUserDefined4("TH");
//				Long countBarcode = proBarcodeMapper.queryCount(tmp);
//				if(countBarcode == 0){
//					barcodeNew.append("20").append(barcode);
//				}else{
//					List<ProBarcode> list = proBarcodeMapper.getMaxBarCode(tmp);
//					if(list.size() > 1){
//						result.setCode(Constant.FAIL);
//						result.setMsg("请联系运维人员");
//						return result;
//					}else{
//						prefix = Integer.valueOf(list.get(0).getBarcode().substring(0,2)) + 1;
//						barcodeNew.append(prefix).append(barcode);
//					}
//				}
//			}else if(prefix >= 20){
//				barcodeNew.append(prefix+1).append(barcodeOld.substring(2));
//			}
//			ProStorageSn storageSn = proStorageSns.get(0);
//			ProBarcode proBarcode = new ProBarcode();
//			proBarcode.setBarcode(barcodeNew.toString());
//			proBarcode.setModel(storageSn.getModel());
//			proBarcode.setProductName(storageSn.getProductName());
//			proBarcode.setDensity(storageSn.getDensity());
//			proBarcode.setSpec(storageSn.getSpec());
//			proBarcode.setGrade(storageSn.getGrade());
//			proBarcode.setLevel(storageSn.getLevel());
//			proBarcode.setMachineNumber(Integer.valueOf(storageSn.getMachineNumber()));
//			proBarcode.setType(storageSn.getType());
////	        proBarcode.setUnit(proCheckIn.getUserDefined1());
//			proBarcode.setUserDefined2(proBarcodeDto.getBatchCode());//批次号
//			proBarcode.setCreateBy(proBarcodeDto.getLoginName());
//			proBarcode.setGmtCreate(new Date());
//			proBarcode.setLastModifiedBy(proBarcodeDto.getLoginName());
//			proBarcode.setGmtModified(new Date());
//			proBarcode.setUnit(storageSn.getUnit());
//			proBarcode.setStatus("0");
//			proBarcode.setUserDefined1("0");
//			proBarcode.setActiveFlag("1");
//			proBarcode.setGmtProduct(new Date());
////		DJ：登记入库，BF：报废入库，TH：退货入库
//			proBarcode.setUserDefined4("TH");
//			proBarcodeMapper.create(proBarcode);
////		往条码打印接口表中插入数据
//			MsbarCode msbarCode = new MsbarCode();
//			msbarCode.setBarCode(barcodeNew.toString());
//			msbarCode.setBarCodeSize(Constant.CODE_ONE);
//			msbarCode.setModel(proBarcode.getModel());
//			msbarCode.setProductName(proBarcode.getProductName());
//			msbarCode.setDensity(proBarcode.getDensity());
//			msbarCode.setSpec(proBarcode.getSpec());
//			msbarCode.setGrade(proBarcode.getGrade());
//			msbarCode.setUpdateDate(new Date());
//			msbarCode.setIsPrint(new Boolean("0"));
//			msbarCode.setBatchCode(proBarcodeDto.getBatchCode());// 批次号
//			msbarCodeMapper.create(msbarCode);
////		退货扫码下线
//			storageSn.setUserDefined4("1");
//			proStorageSnMapper.updateByBarcodeStatus2(storageSn);
//			result.setList(proStorageSns);
//		}else if(proStorageSns.size() > 1){
//			result.setCode(Constant.FAIL);
//			result.setMsg("请联系运维人员");
//		}else{
//			result.setCode(Constant.FAIL);
//			result.setMsg("请扫描退货成品条码！");
//		}
//		return result;
//	}
	@Override
	public TransResult returnsScan(ProBarcodeDto proBarcodeDto){
		TransResult result = new TransResult();
		result.setCode(Constant.SUCCESS);
		ProStorageSn storageSn = new ProStorageSn();
		storageSn.setBarcode(proBarcodeDto.getBarcode());
		storageSn.setActiveFlag("1");
		storageSn.setBarcodeStatus("2");
		List<ProStorageSn> list = proStorageSnMapper.queryByAny(storageSn);
		if(list.size() < 1){
			result.setCode(Constant.FAIL);
			result.setMsg("请扫描退货成品条码！");
		}else{
			String DtoWeight = proBarcodeDto.getWeight();
			if(null == DtoWeight || "".equals(DtoWeight)){
				storageSn.setWeight(list.get(0).getWeight());
			}else {
				storageSn.setWeight(new BigDecimal(proBarcodeDto.getWeight()));
			}
			storageSn.setBarcodeStatus("0");
			storageSn.setUserDefined4("1");
			storageSn.preUpdate();
			storageSn.setLastModifiedBy(proBarcodeDto.getLoginName());
			proStorageSnMapper.updateByBarcodeStatus2(storageSn);
			//添加UserDefined8
			ProBarcode proBarcode = new ProBarcode();
			proBarcode.setBarcode(proBarcodeDto.getBarcode());
			proBarcode.setUserDefined8("TH");
			proBarcodeMapper.updateBySelect(proBarcode);
			storageSn.setModel(list.get(0).getModel());
			ArrayList<ProStorageSn> storageList = new ArrayList<>();
			storageList.add(storageSn);
			result.setList(storageList);
		}
		return result;
	}

    @Override
    public List<ProBarcode> queryPrintListTM(ProBarcode proBarcode) {
        //是否入库 0--未入库 1--已入库
        proBarcode.setUserDefined1("1");
        return proBarcodeMapper.queryPrintListTM(proBarcode);
    }

    @Override
    public List<ProBarcode> queryPrintListSn(List<ProBarcode> dataList) {
        return proBarcodeMapper.queryPrintListSn(dataList);
    }
}
